import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class Transfer extends JPanel implements ActionListener {
    private ATM frame;
    private Icon bgOff = Util.getIcon("/images/buttonOff.jpg");
    private Icon bgsure = Util.getIcon("/images/buttonSure.jpg");
    private JButton offButton = new JButton(bgOff);
    private JButton sureButton = new JButton(bgsure);
    private JTextField textField = new JTextField();
    private JTextField textFieldNew = new JTextField();

    public Transfer(ATM frame) {
        this.frame = frame;
        this.setLayout(null);
        this.setOpaque(false);
        sureButton.setBounds(300, 500, 100, 50);
        this.add(sureButton);
        sureButton.addActionListener(this);
        offButton.setBounds(300, 600, 100, 50);
        this.add(offButton);
        offButton.addActionListener(this);
        JLabel label = new JLabel("输入账户");
        label.setBounds(350, 300, 150, 20);
        this.add(label);
        textField.setBounds(500, 300, 100, 20);
        this.add(textField);
        JLabel labelNew = new JLabel("输入金额");
        labelNew.setBounds(350, 400, 150, 20);
        this.add(labelNew);
        textFieldNew.setBounds(500, 400, 100, 20);
        this.add(textFieldNew);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == offButton) {
            frame.switchPanel("menu");
        } else if (e.getSource() == sureButton) {
            ArrayList<User> list= (ArrayList<User>) FileUtil.readObject("c:/a.txt");
            Double moeny = Double.valueOf(textFieldNew.getText());
            if (moeny > frame.getList().get(frame.getLoginPanel().getIndex()).getMoney()) {
                JOptionPane.showMessageDialog(this, "余额不足");
                return;
            }
            if (textField.getText().equals(frame.getList().get(frame.getLoginPanel().getIndex()).getName())) {
                JOptionPane.showMessageDialog(this, "不能向自己转账");
                return;
            }
            for (int i = 0; i < frame.getList().size(); i++) {
                if (textField.getText().equals(frame.getList().get(i).getName()) && moeny < frame.getList().get(frame.getLoginPanel().getIndex()).getMoney()) {
                    JOptionPane.showMessageDialog(this, "转账成功");
                    frame.getList().get(i).setMoney(frame.getList().get(i).getMoney() + moeny);
                    frame.getList().get(frame.getLoginPanel().getIndex()).setMoney(frame.getList().get(frame.getLoginPanel().getIndex()).getMoney() - moeny);
                    FileUtil.writeObject("c:/a.txt",list);
                    return;
                }
            }
            JOptionPane.showMessageDialog(this, "查无此人");
            frame.switchPanel("zhuan");
        }
    }
}
